package edu.buaa.act.travel.m.service;

import edu.buaa.act.travel.m.Constants;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class RunService extends Service {
	
	private static final int MESSAGE_RUN = 101;
	private static final long FREQUENCY = 3000L;
	
	private Handler mHandler = new Handler() {
		
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case Constants.MESSAGE_GET_DATA_SUCCESS:
				broadcast((String) msg.obj);
				break;
			case MESSAGE_RUN:
				run();
				mHandler.sendEmptyMessageDelayed(MESSAGE_RUN, FREQUENCY);
				break;
			}
		}
	};

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		mHandler.sendEmptyMessage(MESSAGE_RUN);
	}
	
	private void run() {
		new Thread() {
			public void run() {
				DataService.get(Constants.URL_RUN_2, 
						mHandler, 
						Constants.MESSAGE_GET_DATA_SUCCESS, 
						Constants.MESSAGE_GET_DATA_FAIL);
			}
		}.start();
	}
	
	private void broadcast(final String result) {
		Intent intent = new Intent(Constants.BROADCAST_SERVICE);
		intent.putExtra(Constants.EXTRA_RESULT, result);
		sendBroadcast(intent);
	}
}
